//
//  PerWalletRecordViewController.m
//  sklive
//
//  Created by Macx on 2017/7/7.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "PerWalletRecordViewController.h"
//#import "WalletRecordTableViewCell.h"
#import "TransactionTableViewCell.h"
#import "BindingCardViewController.h"

#import "NSString+Common.h"
#import "CashLog.h"
#import "Withdraw.h"
#import "Score.h"
#import "PaymentLog.h"
#import "BankCard.h"
#import "BingLi.h"

#import "WebViewController.h"
#import <Masonry.h>

@interface PerWalletRecordViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property (nonatomic, strong) UITableView *tableView;
//@property (nonatomic, strong) WalletRecordTableViewCell *cell;
@property (nonatomic, strong) NSMutableArray *infoArr;

@property (nonatomic, assign) NSInteger page; // 网络请求页数

@property (nonatomic, strong) BankCard *bankCardInfo; // 银行卡信息

@end

@implementation PerWalletRecordViewController {
    CGSize  _size1;
    CGSize  _size2;
    CGSize  _size3;
    UITextField *_tf;
}


- (void)viewWillAppear:(BOOL)animated {
    
    // 获取获取资金记录
    [self GETRecord];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 进入请求为1
    self.page = 1;
    
    [self buildUI];
    
    [self refreshData];
    
}

#pragma mark ==========构建UI==========
- (void)buildUI {
    
    self.view.backgroundColor = UISeparatedColorRGB;
    
    _size1 = [LZCTools textSizeWithText:@"秀币余额" font:kUHSystemFontWithSize(15)];
    _size2 = [LZCTools textSizeWithText:@"字数" font:kUHSystemFontWithSize(16)];
    _size3 = [LZCTools textSizeWithText:@"请选择支付金额" font:kUHSystemFontWithSize(13)];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-64) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
//    self.tableView.tableFooterView = [[UIView alloc]init];
//    [self.tableView registerNib:[UINib nibWithNibName:@"WalletRecordTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 100;
    self.tableView.tableFooterView = [[UIView alloc]init];
    [self.tableView registerClass:[TransactionTableViewCell class] forCellReuseIdentifier:@"cell"];

    if (self.type == 1) {
        self.navigationItem.title = @"收支明细";
    }
    else if (self.type == 2) {
        
        
        [self GETBankCardInfo];
        
        self.navigationItem.title = @"提现";
        
        CGFloat Y = 0.0;
        
        UILabel *name = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, SCREEN_WIDTH, _size1.height)];
        [self.view addSubview:name];
        name.text = [NSString stringWithFormat:@"   可提现金额(%@元)", self.largestAmount];
        name.font = kUHSystemFontWithSize(15);
        
        Y = name.height+20;
        
        _tf = [[UITextField alloc] initWithFrame:CGRectMake(0, Y, SCREEN_WIDTH, _size3.height*3)];
        [self.view addSubview:_tf];
        _tf.placeholder = @"输入金额(请输入100元以上的整数)";
        _tf.textColor = UIMainColorRGB;
        _tf.backgroundColor = kWhiteColor;
        _tf.keyboardType = UIKeyboardTypeNumberPad;
        _tf.leftViewMode = UITextFieldViewModeAlways; // 出现模式
        UIView *left = [[UIView alloc] initWithFrame:CGRectMake(0, 0 , _size3.height, 0)];
        _tf.leftView = left;
        _tf.delegate = self;
        
        Y = _tf.y+_tf.height+10;
        
        UILabel *name2 = [[UILabel alloc] initWithFrame:CGRectMake(0, Y, SCREEN_WIDTH, _size1.height)];
        [self.view addSubview:name2];
        name2.text = @"   转出银行卡";
        name2.font = kUHSystemFontWithSize(15);
        
        Y = name2.y+name2.height+10;
        
        UIView *cardBgV = [[UIView alloc] initWithFrame:CGRectMake(0, Y, SCREEN_WIDTH, 40)];
        [self.view addSubview:cardBgV];
        cardBgV.backgroundColor = kWhiteColor;
        [cardBgV addTarget:self action:@selector(pushCardBinding)];
        
        UILabel *cardN = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 40)];
        [cardBgV addSubview:cardN];
        cardN.textColor = kGrayColor;
        cardN.font = kUHSystemFontWithSize(15);
        cardN.text = @"   请绑定银行卡";
        cardN.tag = 100;
        
        UIImageView *arrowImg = [[UIImageView alloc] initWithImage:IMAGE(@"arrow_right")];
        [cardBgV addSubview:arrowImg];
        arrowImg.frame = CGRectMake(SCREEN_WIDTH-20, 0, 10, SW(20));
        arrowImg.centerY = cardBgV.height/2;
        
        
        
        Y = Y+cardBgV.height+1;
        
        UIView *btnV = [[UIView alloc] initWithFrame:CGRectMake(0, Y, SCREEN_WIDTH, 60)];
        [self.view addSubview:btnV];
        btnV.backgroundColor = kWhiteColor;
        
        
        
        UIButton *determineBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btnV addSubview:determineBtn];
        determineBtn.frame = CGRectMake(10, 10, SCREEN_WIDTH-20, 40);
        [determineBtn setTitle:@"确定" forState:UIControlStateNormal];
        [determineBtn setBackgroundColor:UIMainColorRGB];
        determineBtn.layer.cornerRadius = 5;
        determineBtn.layer.masksToBounds = YES;
        [determineBtn addTarget:self action:@selector(withdrawalClick:) forControlEvents:UIControlEventTouchUpInside];
        
        UILabel *name3 = [[UILabel alloc] initWithFrame:CGRectMake(0, btnV.y+btnV.height+5, SCREEN_WIDTH, _size1.height)];
        [self.view addSubview:name3];
        name3.text = @"   提现记录";
        name3.font = kUHSystemFontWithSize(15);
        
        Y = name3.y+name3.height+1+5;
        _tableView.frame = CGRectMake(0, Y, SCREEN_WIDTH, SCREEN_HEIGHT-Y-64);
    
    }
    else if (self.type == 3) {
        self.navigationItem.title = @"我的积分";
    }
    else if (self.type == 4) {
        self.navigationItem.title = @"支出记录";
    }
    else if (self.type == 5) {
        self.navigationItem.title = @"我的病历";
//        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"+" style:UIBarButtonItemStyleDone target:self action:@selector(addCase)];
        UIButton * right = [UIButton buttonWithType:UIButtonTypeCustom];
        [right setTitle:@"添加病历" forState:UIControlStateNormal];
        right.titleLabel.font = kUHSystemFontWithSize(14);
        right.frame = CGRectMake(0, 0, [LZCTools textSizeWithText:right.titleLabel.text font:right.titleLabel.font].width, 44);
        right.titleLabel.textAlignment = NSTextAlignmentRight;
        [right setTitleColor:kWhiteColor forState:UIControlStateNormal];
        [right addTarget:self action:@selector(addCase) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:right];
    }
    
}

- (void)addCase {
    
//    查看或修改
//    id：病历ID
//    token：当前用户access token
//http://www.payoujia.com/mobile/mdetails/clinichistory?id=2&token=123
//    添加：
//    token：当前用户access token
//http://www.payoujia.com/mobile/mdetails/clinichistory?token=123
    
    NSString *url = [NSString stringWithFormat:@"http://www.payoujia.com/mobile/mdetails/clinichistory?token=%@", [GetUserDefaule(Token) valueForKey:@"access_token"]];
    WebViewController *webVC = [[WebViewController alloc] init];
    webVC.urlStr = url;
    [self.navigationController pushViewController:webVC animated:YES];
    
}

#pragma mark ==========更新数据==========
- (void)refreshData {
    __weak typeof (self) weakSelf = self;
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"上拉加载");
        weakSelf.page++;
        [weakSelf GETRecord];
    }];
    
//    if (self.type == 5) {
//        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//            NSLog(@"下拉刷新");
//            weakSelf.page = 1;
//            [weakSelf GETRecord];
//        }];
//    }
}

#pragma mark ==========UITableView==========
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    TransactionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.priceLabel.hidden = YES;
//    cell.Label.centerY = cell.contentView.centerY;
    
    if (self.type == 1) {
        CashLog *model = self.infoArr[indexPath.row];
        cell.TextLabel.text = model.remark;
        cell.timeLabel.text = [NSString timeWithTimeIntervalString:model.create_time];
        cell.Label.text = [NSString stringWithFormat:@"%.2lf元", (float)model.money/100];
    }
    else if (self.type == 2) {
        
        Withdraw *model = self.infoArr[indexPath.row];
        cell.TextLabel.text = [NSString stringWithFormat:@"提现%.2lf元", (float)model.amount];
        cell.timeLabel.text = [NSString timeWithTimeIntervalString:[model valueForKey:@"created_at"]];
        //        pending-审核中 passed-批准 reject-拒绝
        if ([model.status isEqualToString:@"pending"]) {
            cell.Label.text = @"审核中";
        }
        else if ([model.status isEqualToString:@"passed"]) {
            cell.Label.text = @"批准";
        }
        else
            cell.Label.text = @"拒绝";
    }
    else if (self.type == 3) {
        Score *model = self.infoArr[indexPath.row];
        cell.TextLabel.text = model.action;
        cell.timeLabel.text = [NSString timeWithTimeIntervalString:[model valueForKey:@"create_time"]];
        if (model.score > 0) {
            cell.Label.text = [NSString stringWithFormat:@"+%ld", model.score];
        }
        else
            cell.Label.text = [NSString stringWithFormat:@"+%ld", model.score];
    }
    else if (self.type == 4) {
        PaymentLog *model = self.infoArr[indexPath.row];
        cell.TextLabel.text = model.remark;
        cell.timeLabel.text = [NSString timeWithTimeIntervalString:[model valueForKey:@"create_time"]];
        cell.Label.text = [NSString stringWithFormat:@"%.2f", (float)model.amount/100];
    }
    else if (self.type == 5) {
        BingLi *model = self.infoArr[indexPath.row];
        //        self.cell.state.text = model.content;
        cell.TextLabel.text = [NSString stringWithFormat:@"病历 %ld", indexPath.row+1];
        cell.timeLabel.text = [NSString timeWithTimeIntervalString:[model valueForKey:@"create_time"]];
        cell.Label.hidden = YES;
    }
    
    [cell.Label mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_offset([LZCTools textSizeWithText:cell.Label.text font:cell.Label.font].width+5);
    }];
    
    return cell;
    
    /*
    self.cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
//    self.cell.model = model;
    
    if (self.type == 1) {
        CashLog *model = self.infoArr[indexPath.row];
        
//        self.cell.state.text = [NSString stringWithFormat:@"充值%ld元", model.money];
        self.cell.state.text = model.remark;
        self.cell.time.text = [NSString timeWithTimeIntervalString:[model valueForKey:@"create_time"]];
        self.cell.money.text = [NSString stringWithFormat:@"%.2lf", (float)model.money/100];

    }
    else if (self.type == 2) {
        Withdraw *model = self.infoArr[indexPath.row];
        self.cell.state.text = [NSString stringWithFormat:@"提现%.2lf元", (float)model.amount/100];
        self.cell.time.text = [NSString timeWithTimeIntervalString:[model valueForKey:@"created_at"]];
        
//        pending-审核中 passed-批准 reject-拒绝
        if ([model.status isEqualToString:@"pending"]) {
            self.cell.money.text = @"审核中";
        }
        else if ([model.status isEqualToString:@"passed"]) {
            self.cell.money.text = @"批准";
        }
        else
            self.cell.money.text = @"拒绝";
        

    }
    else if (self.type == 3) {
        Score *model = self.infoArr[indexPath.row];
        self.cell.state.text = model.action;
        self.cell.time.text = [NSString timeWithTimeIntervalString:[model valueForKey:@"create_time"]];
        if (model.score > 0) {
            self.cell.money.text = [NSString stringWithFormat:@"+%ld", model.score];
        }
        else
            self.cell.money.text = [NSString stringWithFormat:@"+%ld", model.score];
    }
    else if (self.type == 4) {
        PaymentLog *model = self.infoArr[indexPath.row];
        self.cell.state.text = model.remark;
        self.cell.time.text = [NSString timeWithTimeIntervalString:[model valueForKey:@"create_time"]];
        self.cell.money.text = [NSString stringWithFormat:@"%.2f", (float)model.amount/100];
    }
    else if (self.type == 5) {
        BingLi *model = self.infoArr[indexPath.row];
//        self.cell.state.text = model.content;
        self.cell.state.text = [NSString stringWithFormat:@"病历 %ld", indexPath.row+1];
        self.cell.time.text = [NSString timeWithTimeIntervalString:[model valueForKey:@"create_time"]];
        self.cell.money.hidden = YES;
    }
    
    return self.cell;*/
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.infoArr.count;
}
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return SW(7)+20;
//}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"点击tableView.cell = %ld", indexPath.row);
    
    if (self.type == 5) {
        
        
        //    查看或修改
        //    id：病历ID
        //    token：当前用户access token
        //http://www.payoujia.com/mobile/mdetails/clinichistory?id=2&token=123
        //    添加：
        //    token：当前用户access token
        //http://www.payoujia.com/mobile/mdetails/clinichistory?token=123
        
        BingLi *model = self.infoArr[indexPath.row];
        
        NSString *url = [NSString stringWithFormat:@"http://www.payoujia.com/mobile/mdetails/clinichistory?id=%ld&token=%@", model.cId, [GetUserDefaule(Token) valueForKey:@"access_token"]];
        
        
        WebViewController *webVC = [[WebViewController alloc] init];
        webVC.urlStr = url;
        [self.navigationController pushViewController:webVC animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
//    return 30;
    if (self.type == 3) {
        return SW(7)+10+_size1.height;
    }
    return 0;
}
//  自定义分区头的view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (self.type == 3) {
        
        static NSString * identy = @"head";
        UITableViewHeaderFooterView * hf = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identy];
        if (!hf) {
            hf = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:identy];
            
            UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SW(7))];
            [hf addSubview:view];
            view.backgroundColor = kWhiteColor;
            
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
            [view addSubview:btn];
            
            btn.titleLabel.font = kUHSystemFontWithSize(15);
            [btn setImage:[IMAGE(@"icon_me_integral") imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
            [btn setTitleColor:UIMainColorRGB forState:UIControlStateNormal];
            [btn setTitle:@"总积分" forState:UIControlStateNormal];
            
            CGSize btnSize = [LZCTools textSizeWithText:btn.titleLabel.text font:kUHSystemFontWithSize(15)];
            btn.frame = CGRectMake(10, 0, btnSize.width+5+btnSize.height, SW(7));
            
            UILabel *num = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-10-SW(3), 0, SW(3), SW(7))];
            [hf addSubview:num];
            num.textColor = UIMainColorRGB;
            num.text = self.totalScore;
            num.font = kUHSystemFontWithSize(15);
            num.textAlignment = UITextLayoutDirectionRight;
            
            UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(10, view.height, SCREEN_WIDTH-20, 30)];
            [hf addSubview:title];
            title.font = kUHSystemFontWithSize(15);
            title.text = @"积分明细";
            title.textColor = UIMainColorRGB;
        }
        return hf;
    }
    return nil;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    
    if ([textField.text floatValue] > [self.largestAmount floatValue]) {
        textField.text = self.largestAmount;
    }
    
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
	return [self validateNumber:string];
}

- (BOOL)validateNumber:(NSString*)number {
	BOOL res = YES;
	NSCharacterSet* tmpSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
	int i = 0;
	while (i < number.length) {
		NSString * string = [number substringWithRange:NSMakeRange(i, 1)];
		NSRange range = [string rangeOfCharacterFromSet:tmpSet];
		if (range.length == 0) {
			res = NO;
			break;
		}
		i++;
	}
	return res;
}




- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    [textField resignFirstResponder];
    
    if ([textField.text floatValue] > [self.largestAmount floatValue]) {
        textField.text = self.largestAmount;
    }
    
    return YES;
}

#pragma mark ==========响应方法==========
- (void)withdrawalClick:(UIButton *)sender {
    [_tf resignFirstResponder];
    
    if ([_tf.text doubleValue] < 100) {
        [self presentViewController:[LZCTools alertMessage:@"每次提现不得低于100元"] animated:YES completion:nil];
        return;
    }
    
    NSDictionary *param = @{@"amount":_tf.text};
    
    [[NetworkTool sharedTool] requestWithName:@"提现" URLString:APIWithdrawableMoney parameters:param method:@"PUT" callBack:^(id responseObject) {
        [self presentViewController:[LZCTools alertMessage:@"申请提现成功，等待审核中"] animated:YES completion:nil];
        
        [self GETRecord];
        
    }];
    
}

- (void)pushCardBinding {
    NSLog(@"跳到绑定银行卡页面");
    [_tf resignFirstResponder];
    
    BindingCardViewController *bindingVC = [[BindingCardViewController alloc] init];
    bindingVC.cardInfo = self.bankCardInfo;
    [bindingVC returnCard:^(BankCard *model) {
        
        self.bankCardInfo = model;
        
        UILabel *card = [self.view viewWithTag:100];
        card.text = [NSString stringWithFormat:@"   %@", self.bankCardInfo.bank];

    }];
    
    [self.navigationController pushViewController:bindingVC animated:YES];
}

- (void)GETRecord {
    
    NSString *url = APIMoneyLogs;
    
    NSDictionary *param = @{@"page":[NSString stringWithFormat:@"%ld", self.page],
                            @"per_page":@"10"};
    NSString *name = @"获取收支明细";
    if (self.type == 2) {
        url = APIWithdrawableMoney;
        name = @"获取提现记录";
    }
    else if (self.type == 3) {
        url = APIScoreHistories;
        name = @"获取积分记录";
    }
    else if (self.type == 4) {
        url = APIPaymentLogs;
        name = @"获取支出记录";
    }
    
    else if (self.type == 5) {
        url = APIClinichistories;
        name = @"获取病例记录";
    }
    
    
    [[NetworkTool sharedTool] requestWithName:name URLString:url parameters:param method:@"GET" callBack:^(id responseObject) {
        NSArray *arr = responseObject[@"data"];
        
        if (self.page == 1) {
            [self.infoArr removeAllObjects];
            
        }
        if (arr.count == 0) {
            self.page--;
            if (self.page == 0) {
                self.page = 1;
            }
        }
        
        
        for (NSDictionary *dic in arr) {
            if (self.type == 1) {
                CashLog *model = [[CashLog alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.infoArr addObject:model];

            }
            else if (self.type == 2) {
                Withdraw *model = [[Withdraw alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.infoArr addObject:model];
            }
            else if (self.type == 3) {
                Score *model = [[Score alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.infoArr addObject:model];
            }
            else if (self.type == 4) {
                PaymentLog *model = [[PaymentLog alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.infoArr addObject:model];
            }
            else if (self.type == 5) {
                BingLi *model = [[BingLi alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.infoArr addObject:model];
            }
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [_tableView.mj_footer endRefreshing];
            [_tableView reloadData];
        });
    }];
    
}

/**
 获取银行卡信息
 */
- (void)GETBankCardInfo {
    [[NetworkTool sharedTool] requestWithName:@"获取银行卡信息" URLString:APIBankcards parameters:nil method:@"GET" callBack:^(id responseObject) {
       
        UILabel *card = [self.view viewWithTag:100];
        
        if (responseObject[@"data"]) {
            self.bankCardInfo = [[BankCard alloc] init];
            [self.bankCardInfo setValuesForKeysWithDictionary:responseObject[@"data"]];
            card.text = [NSString stringWithFormat:@"   %@", self.bankCardInfo.bank];
        }
        else
            card.text = @"xx";
        
    }];
}

// 懒加载
- (NSMutableArray *)infoArr {
    if (_infoArr == nil) {
        _infoArr = [[NSMutableArray alloc] init];
    }
    return _infoArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
